# -*- coding: utf-8 -*-
from django.contrib.auth import get_user_model
from rest_framework import serializers

from moments.models import WeChatUser


class WeChatUserSerializer(serializers.ModelSerializer):
    
    user = serializers.CharField(required=True, max_length=10)
    
    class Meta:
        model = WeChatUser
        fields = ["id", "user", "motto", "region", "email"]

    def create(self, validated_data):
        user_cls = get_user_model()
        user, is_created = user_cls.objects.get_or_create(username=validated_data["user"])
        validated_data["user"] = user
        return super(WeChatUserSerializer, self).create(validated_data)

    def update(self, instance, validated_data):
        validated_data.pop("user", None)
        return super(WeChatUserSerializer, self).update(instance, validated_data)
